import {
  ALL,
  Body,
  Context,
  Controller,
  Get,
  Inject,
  Post,
  Provide,
} from '@midwayjs/core';
import { AuthService } from '../service/auth';
import { LoginDTO } from '../dto/login';
import { RSAService } from '../../../common/rsa.service';
import { requiredString } from '../../../common/common.validate.rules';
import { Valid } from '@midwayjs/validate';
import { NotLogin } from '../../../decorator/not.login';
import { RedisService } from '@midwayjs/redis';
import { R } from '../../../common/base.error.util';
import { ResetPasswordDTO } from '../dto/reset.password';

@Provide()
@Controller('/auth')
export class AuthController {
  @Inject()
  authService: AuthService;

  @Inject()
  rsaService: RSAService;

  @Inject()
  redisService: RedisService;

  @Inject()
  ctx: Context;

  @Post('/login', { description: '登录' })
  @NotLogin()
  async login(@Body(ALL) loginDTO: LoginDTO) {
    return await this.authService.login(loginDTO);
  }
  @Post('/logout', { description: '退出登录' })
  async logout() {
    // 清除token和refreshToken
    const res = await this.redisService
      .multi()
      .del(`token:${this.ctx.token}`)
      .del(`refreshToken:${this.ctx.userInfo.refreshToken}`)
      .exec();

    if (res.some(item => item[0])) {
      throw R.error('退出登录失败');
    }

    return true;
  }

  @Get('/current/user', { description: '获取当前用户信息' })
  async getCurrentUser() {
    // return await this.authService.getUserById(this.ctx.userInfo.userId);
  }

  @Get('/publicKey', { description: '获取RSA公钥' })
  @NotLogin()
  async getPublicKey() {
    return await this.rsaService.getPublicKey();
  }

  @Post('/refresh/token', { description: '刷新token' })
  async refreshToken(@Valid(requiredString) refreshToken: string) {
    return this.authService.refreshToken(refreshToken);
  }

  @Post('/reset/password', { description: '重置密码' })
  async resetPassword(@Body() resetPasswordDTO: ResetPasswordDTO) {
    await this.authService.resetPassword(resetPasswordDTO);
  }
}
